package com.gemcoder.system.service;

import com.gemcoder.system.bo.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.List;

import static com.gemcoder.system.datasource.JdbcTemplateUtil.executeSQL;

@Service
public class UserSdkService {

    /**
     * 获取用户信息
     */
    public Result getUser(Map<String,Object> paramMap) {

        String username = (String) paramMap.get("user_name");
        String sql = "select * from users where user_name = ?";
        return new Result(true, "success", executeSQL(sql,username));
    }

    /**
     * 获取当前登录用户名
     */
    public static String sdkOfGetCurrentUserName() {

        //获取当前用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null; // 用户未认证
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }
        return null; // 无法获取用户名
    }

    /**
     * 获取当前登录用户的用户id
     */
    public static Integer sdkOfGetCurrentUserId() {

        //获取当前用户名
        String userName = sdkOfGetCurrentUserName();
        if (userName != null) {
            String sql = "select id from users where user_name = '" + userName + "' limit 1";
            List<Map<String, Object>> users = (List<Map<String, Object>>)executeSQL(sql);
            Object id = users.get(0).get("id");
            return (Integer) id;
        }
        return 0; // 无法获取用户名
    }




}
